<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回顶部</title>
    <style>
        .content {
            height: 2000px;
        }

        #goTop {
            width: 100px;
            height: 100px;
            background-color: #756e6e57;
            text-align: center;
            line-height: 100px;
            position: fixed;
            bottom: 100px;
            right: 20px;
        }
    </style>
</head>

<body>
    <div class="content">
        <h2>返回首屏</h2>
        <div id="goTop">返回</div>
    </div>
    <script>


        // let goTop = document.getElementById('goTop');

        // window.onscroll = () => {
        //     // 元素绑定
        //     let res = document.body.scrollTop || document.documentElement.scrollTop;
        //     console.log(res);
        //     if (res >= 400) {
        //         goTop.style.display = 'block';
        //     } else {
        //         goTop.style.display = 'none';
        //     }
        // }

        // goTop.onclick = () => {
        //     document.body.scrollTop = 0;
        //     document.documentElement.scrollTop = 0;
        // }

        let goTop = document.getElementById('goTop');
        window.onscroll = () => {
            let res = document.documentElement.scrollTop;
            if (res >= 400) {
                goTop.style.display = 'block';
            } else {
                goTop.style.display = 'none';
            }
        }
        goTop.onclick = () => {
            document.documentElement.scrollTop = 0;
        }


    </script>
</body>

</html>